﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using EntityAndDomainLibrary.DomainModel;
using System.Threading;
using Log4NetLibrary;
using System.Timers;

namespace MeterService.Helpers
{
    public  class FileWatcher
    {
        #region Private Variables
        private  FileSystemWatcher _watcher;
        DataBaseAccess dbAccess = new DataBaseAccess();

        ILogService logService;
        System.Timers.Timer timer;
        #endregion

        public  void Intialize()
        {
            try
            {

                log4net.Config.XmlConfigurator.Configure();
                logService = new FileLogService(typeof(FileWatcher));

                _watcher = new FileSystemWatcher();

                int interval = Convert.ToInt32((System.Configuration.ConfigurationSettings.AppSettings["interval"]));

                timer = new System.Timers.Timer(interval);
                timer.Elapsed+=new System.Timers.ElapsedEventHandler(timer_Elapsed);

                ReadAllFilesOnStart();
                ////_watcher.Changed += new FileSystemEventHandler(FileSystemChanged);
                //_watcher.Created += new FileSystemEventHandler(FileSystemCreated);

                //_watcher.Path = dbAccess.GetSystemSettings().FileLocation;
                //_watcher.EnableRaisingEvents = true;
            }

            catch (Exception ex)
            {
                logService.Error(ex.Message);
            }
        }

        #region Events
        void timer_Elapsed(object source, ElapsedEventArgs e)
        {
            ReadAllFilesOnStart();
        }

        void FileSystemChanged(object sender, FileSystemEventArgs e)
        {
            try
            {
                //new Thread(() =>
                //    {
                        string filename = e.Name;
                        string archievepath = dbAccess.GetSystemSettings().ArchiveLocation + "\\" + e.Name;

                        FileArchive archive = dbAccess.SaveFileArchive(archievepath);
                        ReadWriteHelper.ReadAndWriteToDB(e.FullPath, archive);

                        ReadAndArchieveFile(e.FullPath, archievepath);
                    //}).Start();
            }

            catch (Exception ex)
            {
                logService.Error(ex.Message);
            }
        }

        void FileSystemCreated(object sender, FileSystemEventArgs e)
        {
            try
            {
                //new Thread(() =>
                //    {
                        string filename = e.Name;
                        string archievepath = dbAccess.GetSystemSettings().ArchiveLocation + "\\" + e.Name;

                        FileArchive archive = dbAccess.SaveFileArchive(archievepath);
                        ReadWriteHelper.ReadAndWriteToDB(e.FullPath, archive);

                        ReadAndArchieveFile(e.FullPath, archievepath);
                    //}).Start();
            }

            catch (Exception ex)
            {
                logService.Error(ex.Message);
            }
        } 
        #endregion

        #region Helpers
        void ReadAllFilesOnStart()
        {
            try
            {
                //new Thread(() =>
                //    {
                timer.Stop();
                        SystemSetting systemsettings = dbAccess.GetSystemSettings();
                        foreach (string file in Directory.EnumerateFiles(systemsettings.FileLocation,
                                                                "*.*"))
                        {
                            FileArchive archive = dbAccess.SaveFileArchive(systemsettings.ArchiveLocation);
                            ReadWriteHelper.ReadAndWriteToDB(file, archive);

                            string[] archievepath = file.Split('\\');
                            ReadAndArchieveFile(file, systemsettings.ArchiveLocation + @"\" + archievepath[2]);
                        }
                    //}).Start();

                        timer.Start();
            }

            catch (Exception ex)
            {
                logService.Error(ex.Message);
            }
        }

        void ReadAndArchieveFile(string sourcelocation, string destlocation)
        {
            try
            {
                if (System.IO.File.Exists(destlocation))
                    System.IO.File.Delete(destlocation);

                System.IO.File.Move(sourcelocation, destlocation);
            }

            catch (Exception ex)
            {
                logService.Error(ex.Message);
            }

        }

        //public void WriteFile()
        //{
        //    try
        //    {
        //        ReadWriteHelper.WriteDataToOutputFile(dbAccess.GetSystemSettings().OutputFileLocation);
        //    }

        //    catch (Exception ex)
        //    {
        //        logService.Error(ex.Message);
        //    }


        //}
        #endregion
    }
}
